package com.haowan123.qinmeiren.appota2;

import java.io.File;

import com.android.mylib.Interface;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class LoadingScreen extends Activity {
	private SeekBar downloadProgress;
	private double currentByte;
	private double totalBytes;
	private TextView downloadIndicator;
	private ProgressObserver observer = new ProgressObserver();
	private Handler handler ;
	private int stt=-1;
	private ProgressDialog loading;
	private Interface helper;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_loading_screen);
		handler = new Handler();
		helper= UIApp.getHelper();
		downloadProgress=(SeekBar)findViewById(R.id.downloadProgress);
		downloadProgress.setMax(100);
		loading = new ProgressDialog(this);
		loading.setMessage(getResources().getString(R.string.loading));
		loading.setCancelable(false);
		LayerDrawable ld = (LayerDrawable) downloadProgress.getProgressDrawable();
		downloadProgress.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return true;
			}});
		downloadIndicator=(TextView) findViewById(R.id.downloadIndicator);
		IntentFilter filter=new IntentFilter();
		filter.addAction(Constants.UPDATE_PROGRESS_ACTION);
		filter.addAction(Constants.DOWNLOAD_COMPLETE_ACTION);
		registerReceiver(observer, filter);
		firstStep();
	}
	@Override
	protected void onDestroy() {
		Log.e("","onDestroy");
		unregisterReceiver(observer);
		super.onDestroy();
	}
	
	private class ProgressObserver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(Constants.UPDATE_PROGRESS_ACTION)){
				currentByte=intent.getDoubleExtra(Constants.CURRENT_PROGRESS, 0f);
				totalBytes=intent.getDoubleExtra(Constants.TOTAL_PROGRESS, 1f);
				updateDownloadProgress(currentByte, totalBytes);
			}else{
				if(!UIApp.canOpenfile()){
					downloadIndicator.setText("");
					finish();
					return;
				}
				finishDownload();
			}
		}
    	
    }
	
	public void updateDownloadProgress(double currentbyte,double totalbytes){
    	if(currentbyte==totalbytes){
    		//finish download
    		downloadProgress.setProgress(0);
    		downloadProgress.setVisibility(View.GONE);
    	}else{
    		if(totalbytes!=0){
				downloadProgress.setVisibility(View.VISIBLE);
    			downloadProgress.setProgress((int) (currentbyte*100/totalbytes));
    			downloadIndicator.setText(getResources().getString(R.string.loading_percent, (int) (currentbyte*100/totalbytes)));
    		}
    	}
    	
    }
    public void finishDownload(){
    	downloadIndicator.setText("");
    	Intent intent = new Intent(Intent.ACTION_VIEW);
    	intent.setDataAndType(Uri.fromFile(new File(Constants.PATH)),"application/vnd.android.package-archive");
    	startActivity(intent);
    	finish();
    }

	private void doDownload() {
		Intent dl=new Intent(this, DownloadService.class);
		dl.setAction("DLA");
		UIApp.allowOpenForNewDownload();
		startService(dl);
	}
	
	
	
	///
	
	
	private void firstStep(){
		if(CommonUtils.checkNetworkAvaliable(this)){
			handler.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					doGet();
				}
			}, 100);
		}else{
			AlertDialog.Builder builder=new Builder(this);
			builder.setMessage(getResources().getString(R.string.check_network)).setPositiveButton(getResources().getString(R.string.retry), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if(CommonUtils.checkNetworkAvaliable(LoadingScreen.this)){
						loading.show();
						doGet();
					}else{
						Toast.makeText(LoadingScreen.this, getResources().getString(R.string.check_network), Toast.LENGTH_SHORT).show();
					}
				}
			}).setNegativeButton(getResources().getString(R.string.exit), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					continueScreen();
				}
			}).setCancelable(false).show();
		}
	}
	
	private void doGet() {
		if(stt!=-1){
			UIApp.setSTT(stt);
			continueScreen();
		}else{
			stt=helper.init(CommonUtils.getDeviceId(this), getApplicationContext().getPackageName(), CommonUtils.sdCardPath());
			if(stt==-1){
				UIApp.setSTT(stt);
				//still wait for another 1500ms
				handler.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						if(loading!=null && loading.isShowing()){
							loading.dismiss();
						}
						continueScreen();
					}
				}, 1500);
			}else{
				if(loading!=null && loading.isShowing()){
					loading.dismiss();
				}
				continueScreen();
			}
			
		}
	}
	
	private void continueScreen(){
		if(CommonUtils.isFileAvaiable(LoadingScreen.this)){
			Intent intent=new Intent(LoadingScreen.this,	FirstActivity.class);
			startActivity(intent);
			finish();
		}else
		if(stt==1){
			doDownload();
		}else {
			Intent intent=new Intent(LoadingScreen.this,	FirstActivity.class);
			startActivity(intent);
			finish();
		}
		
	}
}
